//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#ifndef __ELASTOS_TSHARING_H__
#define __ELASTOS_TSHARING_H__

#define TIMESHARING_NUMBEROF_PRIORITIES   32  // 0 ~ 31
#define TIMESHARING_MIN_PRIORITY          0
#define TIMESHARING_MAX_PRIORITY          (TIMESHARING_NUMBEROF_PRIORITIES - 1)

#define TIMESHARING_QUOTAS_PER_TICK       3

#define TIMESHARING_DEFAULT_PRIORITY      15

//
// TimeSharingScheduleClass
//
class TimeSharingScheduleClass : public ScheduleClass
{
public:
    virtual void Initialize();

    virtual void InitializeThread(Thread *pThread);

    virtual void SetThreadPriority(
        Thread *pThread, ThreadPriority priority, bool_t bRunning);
    virtual ThreadPriority GetThreadPriority(Thread *pThread);

    virtual void OnThreadSleep(Thread *pThread);
    virtual void OnThreadWakeUp(Thread *pThread);

    virtual void OnThreadYield(Thread *pThread);

    virtual void OnThreadSwitchOut(Thread *pThread);

    virtual void EnterRunningList(Thread *pThread, RunningReason reason);

    virtual void LeaveRunningList(Thread *pThread);

    virtual void UpdateTime(uint_t uTicks);
    virtual bool_t UpdateThreadTime(Thread *pThread, uint_t uTicks);

    virtual Thread *SelectNextThread();

public:
    TimeSharingScheduleClass();

    void PromoteHungryThreads();

private:
    void RecalcMaxActivePriority(int nNewActivePriority);

    bool_t UpdatePriorityByQuota(Thread *pThread);

    void TryToPromoteHungryThread(Thread *pThread);

private:
    uint_t          m_uElapsedTicks;

    DLinkNode       m_listHeads[TIMESHARING_NUMBEROF_PRIORITIES];
    int             m_nMaxActivePriority;

    // schedule tables
    STATIC uint_t   s_uMaxDynamicPriorities[TIMESHARING_NUMBEROF_PRIORITIES];

    STATIC uint_t   s_uHighDynamicPriorities[TIMESHARING_NUMBEROF_PRIORITIES];
    STATIC uint_t   s_uLowDynamicPriorities[TIMESHARING_NUMBEROF_PRIORITIES];

    STATIC int      s_nBaseTimeQuotas[TIMESHARING_NUMBEROF_PRIORITIES];
    STATIC int      s_nMaxTimeQuotas[TIMESHARING_NUMBEROF_PRIORITIES];

    STATIC uint_t   s_uReadyTickLimits[TIMESHARING_NUMBEROF_PRIORITIES];
    STATIC uint_t   s_uPriorityIncrements[TIMESHARING_NUMBEROF_PRIORITIES];
    STATIC uint_t   s_uTimeQuotaIncrements[TIMESHARING_NUMBEROF_PRIORITIES];
};

EXTERN TimeSharingScheduleClass g_timeSharingScheduleClass;

#endif // __ELASTOS_TSHARING_H__
